package com.module.mail;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.phprpc.util.AssocArray;
import org.phprpc.util.PHPSerializer;
import org.xsocket.connection.INonBlockingConnection;

import com.command.Group;
import com.connect.agreement.Packet;
import com.game.database.MysqlHelper;
import com.game.manager.CommManager;
import com.game.manager.ErrorManager;
import com.game.manager.SobManager;
import com.game.performers.Actor;
import com.module.regrole.RegRoleManager;

public class MailManager {
	public static final byte SendMail = 1;
	public static final byte GetMails = 2;
	public static final byte GetContent = 3;
	public static final byte DeleteMails = 4;
	public static List<MailTitle> getMailsById(int id){
		Object[] parms = new Object[1];
		parms[0] = id;
		try {
			ArrayList list = MysqlHelper.ExecuteReader("select `id`,`title`,`ctime`,`fromid`,`fromname`,`state`,`owner`,`cid`,`accessory` from user_mail_title where owner = ?", parms);
			List<MailTitle> ret = new ArrayList<MailTitle>();
			for(Object item : list){
				MailTitle title = new MailTitle();
				Object[] row = (Object[]) item;
				title.id = (Integer)row[0];
				title.title = (String)row[1];
				title.ctime = (Integer)row[2];
				title.fromid = (Integer)row[3];
				title.fromname = (String)row[4];
				title.state = (Integer)row[5];
				title.owner = (Integer)row[6];
				title.cid = (Integer)row[7];
				title.accessory = (Integer)row[8];
				ret.add(title);
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static MailTitle getMailTitleById(int id){
		Object[] parms = new Object[1];
		parms[0] = id;
		try {
			Map<String, Object> ret = MysqlHelper.ExecuteRow("select * from user_mail_title where id = ?", parms);
			if(ret == null){
				return null;
			}
			MailTitle title = new MailTitle();
			title.id = (Integer)ret.get("id");
			title.title = (String)ret.get("title");
			title.ctime = (Integer)ret.get("ctime");
			title.fromid = (Integer)ret.get("fromid");
			title.fromname = (String)ret.get("fromname");
			title.state = (Integer)ret.get("state");
			title.owner = (Integer)ret.get("owner");
			title.cid = (Integer)ret.get("cid");
			title.accessory = (Integer)ret.get("accessory");
			return title;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static MailContent getContentByCid(int cid){
		Object[] parms = new Object[1];
		parms[0] = cid;
		try {
			Map<String, Object> ret = MysqlHelper.ExecuteRow("select * from user_mail_content where id = ?", parms);
			if(ret == null){
				return null;
			}
			MailContent content = new MailContent();
			content.id = (Integer)ret.get("id");
			content.content = (String)ret.get("content");
			String items = (String)ret.get("itemids");
			if(items!=null && !items.isEmpty()){
				String[] itemlist = items.split(",");
				content.items = new ArrayList<Integer>();
				for(String item : itemlist){
					content.items.add(Integer.parseInt(item));
				}
			}
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void sendMail(SendMailInfo info,INonBlockingConnection nbc){
		int roleid = RegRoleManager.getRoleId(info.towho);
		if(roleid == 0){
			ErrorManager.sendError(nbc, ErrorManager.NonRole);
			return;
		}
		Actor fromrole = (Actor)SobManager.get().getSob(info.fromrid);
		if(fromrole == null){
			ErrorManager.sendError(nbc, ErrorManager.NonRole);
			return;
		}
		int ret = sendMail(info.title,info.content,info.fromrid,fromrole.getName(),roleid);
		if(ret>0){
			try {
				Packet packet = new Packet();
				packet.setBuffer(Group.Mail, SendMail, new PHPSerializer().serialize(true),true);
				nbc.write(packet.byteBuffer());
			} catch (Exception e) {
				ErrorManager.sendError(nbc, ErrorManager.SendPacket);
			}
			MailTitle mailtitle = getMailTitleById(ret);
			INonBlockingConnection conn = CommManager.get().getConn(roleid);
			
			if(conn!=null){
				try {
					Packet packet = new Packet();
					packet.setBuffer(Group.Mail, SendMail, new PHPSerializer().serialize(mailtitle),true);
					conn.write(packet.byteBuffer());
				} catch (Exception e) {
					ErrorManager.sendError(nbc, ErrorManager.SendPacket);
				}
			}
			
		}
	}
	
	public static int sendMail(String title,String content,int fromrid, String fromname, int torid){
		try {
			Object[] parms = new Object[1];
			parms[0] = content;
			String sql = "insert into user_mail_content (`content`,`itemids`) values (?,'')";
			int cid = MysqlHelper.ExecuteInsert(sql, parms);
			parms = new Object[5];
			parms[0] = title;
			parms[1] = fromrid;
			parms[2] = fromname;
			parms[3] = torid;
			parms[4] = cid;
			sql = "insert into user_mail_title (`title`,`ctime`,`fromid`,`fromname`,`owner`,`cid`) values (?,unix_timestamp(),?,?,?,?)";
			return MysqlHelper.ExecuteInsert(sql, parms);
		} catch (Exception e) {
			return 0;
		}
	}
	
	public static void readMail(int id){
		Object[] parms = new Object[1];
		parms[0] = id;
		try {
			MysqlHelper.ExecuteNoneQuery("update user_mail_title set state = 2 where id = ?", parms);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static boolean deleteMails(String ids,INonBlockingConnection nbc){
		Object[] parms = new Object[1];
		parms[0] = ids;
		try {
			MysqlHelper.ExecuteNoneQuery("update user_mail_title set state = 3 where id in (?)", parms);
			return true;
		} catch (Exception e) {
			ErrorManager.sendError(nbc, ErrorManager.SqlError);
			e.printStackTrace();
			return false;
		}
	}
	
	public static void update(INonBlockingConnection nbc,Packet packet){
		if(packet==null){
			return;
		}
		if(!nbc.isOpen()){
			return;
		}
		try {
			Packet retpacket = null;
			Actor role = CommManager.get().roles.get(nbc.getId());
			if(role == null){
				ErrorManager.sendErrorMsg(nbc, "您未进入游戏");
			}
			switch(packet.getCmd()){
			case SendMail:
				SendMailInfo info = (SendMailInfo)new PHPSerializer().unserialize(packet.getContent());
				sendMail(info,nbc);
				break;
			case GetMails:
				Integer rid = (Integer)new PHPSerializer().unserialize(packet.getContent());
				if(rid!=null){
					List<MailTitle> list = getMailsById(rid);
					retpacket = new Packet();
					retpacket.setBuffer(Group.Mail, GetMails, new PHPSerializer().serialize(list),true);
				} else {
					ErrorManager.sendErrorMsg(nbc, "角色id有误，获取不到邮件内容");
				}
				break;
			case GetContent:
				AssocArray ids = (AssocArray)new PHPSerializer().unserialize(packet.getContent());
				int cid = (Integer)ids.get(0);
				if(ids.size()>1){
					int id = (Integer)ids.get(1);
					readMail(id);
				}
				MailContent content = getContentByCid(cid);
				if(content!=null){
					retpacket = new Packet();
					retpacket.setBuffer(Group.Mail, GetContent, new PHPSerializer().serialize(content),true);
				} else {
					ErrorManager.sendErrorMsg(nbc, "找不到cid="+cid+"的信件内容");
				}
				break;
			case DeleteMails:
				String deleteids = (String)new PHPSerializer().unserialize(packet.getContent(),String.class);
				if(deleteMails(deleteids,nbc)){
					packet.setBuffer(packet.getGroupcmd(), packet.getCmd(), (byte[])null,true);
					nbc.write(packet.byteBuffer());
				}
				break;
			}
			if(retpacket!=null)
				nbc.write(retpacket.byteBuffer());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
